<?php

namespace App\Http\Controllers\Api;

use App\AgentOrder;
use App\Course;
use App\Http\Services\DomainManager;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;
use App\IntegralDetail;
use App\OrderItem;
use App\Orders;
use App\SystemGroup;
use App\User;
use App\UserGroup;
use App\UserGroupXUser;
use App\VipInfo;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\Exception;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Endroid\QrCode\QrCode;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Facades\Image;

class PaymentController extends Controller
{
    public function weChatPayment(Request $request){
//        $enterpriseId=DomainManager::getEnterpriseId($request);
//        if (!$enterpriseId)
//            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $orderNum = $request->get('order_num');

        /** @var Orders $thisOrder */
        $thisOrder = Orders::whereOrderNum($orderNum)
            ->whereUserId($user->id)
            ->first();
        if(!$thisOrder)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        if($thisOrder->is_pay == 1)
            return response()->json(['level' => 'error','message' => '订单已支付']);

        if($thisOrder->vip_type == 'num'){
            $vipInfo = VipInfo::whereUserId($user->id)->whereType('num')->whereColumn('num','>','use_num')->first();
            if(!$vipInfo)
                return response()->json(['level' => 'error','message' => '会员次数已用尽']);
        }elseif($thisOrder->vip_type == 'time'){
            $vipInfo = VipInfo::whereUserId($user->id)->whereType('time')->where('end_time','>',date('Y-m-d H:i:s',time()))->first();
            if(!$vipInfo)
                return response()->json(['level' => 'error','message' => '会员已过期']);
        }

//        if($thisOrder->status == 1 && (strtotime($thisOrder->created_at) + (30 * 60)) < time()){
//            $thisOrder->status = 6;
//            $thisOrder->save();
//            return response()->json(['level' => 'error','message' => '订单已取消']);
//        }


//        $config = DomainManager::getPayConfig($request);
        $config = [
            // 必要配置
            'app_id'             => env('WXAPP_KEY'),
            'mch_id'             => env('WECHAT_PAYMENT_MERCHANT_ID'),
            'key'                => env('WECHAT_PAYMENT_KEY'),   // API 密钥
        ];

        if (!$config){
            \Log::notice('weChatPayment:$config=>'.var_dump($config));
            return response()->json(['level' => 'error','message' => '微信支付配置错误']);
        }

        if (!$config['app_id'] || !$config['mch_id'] || !$config['key'])
            return response()->json(['level'=>'error','message'=>'未配置微信支付信息']);

        $app = Factory::payment($config);
        try {
            $result = $app->order->unify([
                'body' => '法律服务',
                'out_trade_no' => $thisOrder->order_num,
                'total_fee' => (float)$thisOrder->pay_amount * 100,
                'spbill_create_ip' => '', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                'notify_url' => route('Api.Payment.WeChatPayCallback'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'openid' => $user->wx_openid,
            ]);
        } catch (InvalidArgumentException $e) {
            return response()->json(['level'=>'error','message'=>'InvalidArgumentException:'.$e->getMessage()]);
        } catch (InvalidConfigException $e) {
            return response()->json(['level'=>'error','message'=>'InvalidConfigException:'.$e->getMessage()]);
        } catch (GuzzleException $e) {
            return response()->json(['level'=>'error','message'=>'GuzzleException:'.$e->getMessage()]);
        }


        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
            $jssdk = $app->jssdk;
            $prepayId = $result['prepay_id'];
            $json = $jssdk->bridgeConfig($prepayId); // 返回 json 字符串，如果想返回数组，传第二个参数 false

            return response()->json(['level' => 'success','message' => '支付订单创建成功','data'=>json_decode($json)]);
        }else{
            \Log::error('支付订单创建失败，错误信息：'.$result['return_message']);
            return response()->json(['level' => 'error','message' => '支付订单创建失败','data' => $result]);
        }
    }

    /**
     * 获取支付二维码
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws \Endroid\QrCode\Exceptions\ImageTypeInvalidException
     */
    public function getPayQrCode(Request $request){
        $codeUrl = !is_null($request->get('code_url')) ? $request->get('code_url') : '';

        $url = $codeUrl;
        $qrCode = new QrCode();
        $qrCode
            ->setText($url)
            ->setSize(250)
            ->setPadding(10)
            ->setErrorCorrection('high')
            ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
            ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
            ->setImageType(QrCode::IMAGE_TYPE_PNG)
        ;

        $qrcodeContent = $qrCode->getImage();

        $qrcodeContentImg = Image::make($qrcodeContent);

        $response = response()->make($qrcodeContentImg->encode('png'));
        $response->header('Content-Type', 'image/png');

        return $response;
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPayStatus(Request $request){
        $orderNum = !is_null($request->get('order_num')) ? $request->get('order_num') : '';
        $type     = !is_null($request->get('type')) ? $request->get('type') : 2;

        $order = Orders::whereOrderNum($orderNum)->first();
        if(!$order)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        if($type == 2){
            if($order->is_pay == 1){
                return response()->json(['level' => 'success','message' => '订单支付成功','data' => $order->is_pay]);
            }else{
                return response()->json(['level' => 'error','message' => '订单支付失败','data' => $order->is_pay]);
            }
        }elseif($type == 1){
            return response()->json(['level' => 'error','message' => '订单已取消']);
        }else{
            return response()->json(['level' => 'error','message' => '系统错误']);
        }

    }

    //微信支付回调
    public function WeChatPayCallback(Request $request){
//        $enterpriseId=DomainManager::getEnterpriseId($request);
//        if (!$enterpriseId)
//            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

//        $config = DomainManager::getPayConfig($request);
        $config = [
            // 必要配置
            'app_id'             => env('WXAPP_KEY'),
            'mch_id'             => env('WECHAT_PAYMENT_MERCHANT_ID'),
            'key'                => env('WECHAT_PAYMENT_KEY'),   // API 密钥
        ];
        $app = Factory::payment($config);

        $response = $app->handlePaidNotify(function ($message, $fail) {
            $ordersNum = $message['out_trade_no'];

            /** @var Orders $order */
            $order = Orders::whereOrderNum($ordersNum)->first();
            if (!$order || ($order && $order->is_pay == 1)) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    $order->pay_time = date('Y-m-d H:i:s', time()); // 更新支付时间为当前时间
                    $order->pay_way = 'wechatpay';
                    $order->is_pay = 1;
                    $order->save(); // 保存订单
                    if ($order->group_id){
                        $thisGroupUser=UserGroupXUser::whereUserId($order->user_id)
                            ->whereUserGroupId($order->group_id)
                            ->first();
                        if ($thisGroupUser){
                            if ($thisGroupUser->status == 0){
                                $thisGroupUser->status = 1;
                                $thisGroupUser->save();
                            }
                        }

                        $userGroup=UserGroup::whereId($order->group_id)->first();
                        if ($userGroup){
                            if (($userGroup->user_id == $order->user_id) && $userGroup->status == 0){
                                $userGroup->status = 1;
                                $userGroup->save();
                            }

                            if ($userGroup->status == 1 || $userGroup->status ==2){
                                $sysGroup = SystemGroup::whereId($userGroup->system_groups_id)->first();
                                if ($sysGroup){
                                    $groupUser = UserGroupXUser::whereUserGroupId($order->group_id)
                                        ->whereStatus(1)
                                        ->get();
                                    if (count($groupUser) >= $sysGroup->require_num){
                                        //拼团成功
                                        $userGroup->status = 2;
                                        $userGroup->save();
                                        $order->is_success = 1;
                                        $order->save();
                                        if (count($groupUser) > 0){
                                            foreach ($groupUser as $UserGroupXUser){
                                                $UserGroupXUser->status=2;
                                                $UserGroupXUser->save();
                                            }
                                        }
                                    }
                                }

                            }
                        }


                    } else {
                        $order->is_success = 1;
                        $order->save();
                    }

                    if($order->vip_type == 'num'){
                        $vipInfo = VipInfo::whereUserId($order->user_id)->whereType('num')->whereColumn('num','>','use_num')->first();
                        if($vipInfo){
                            $vipInfo->use_num += 1;
                            $vipInfo->save();
                        }
                    }

                    try {
                        AgentOrder::addAgentOrder($order->user_id,$order->order_num);
                    } catch (\Exception $e){
                        Log::error('addAgentOrder：添加推广订单失败，message=>' . $e->getMessage());
                    }

                    if(!empty($order->invite_user_id)){
                        IntegralDetail::addIntegral($order->invite_user_id,0,0,$order->id);
                    }
                }
//                elseif ($message['result_code'] === 'FAIL') {
//                    //用户支付失败
//
//                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            return true; // 返回处理完成
        });
        return $response;
    }

    public static function refundConfig(){
        $config = [
            // 必要配置
            'app_id'             => env('WXAPP_KEY'),
            'mch_id'             => env('WECHAT_PAYMENT_MERCHANT_ID'),
            'key'                => env('WECHAT_PAYMENT_KEY'),   // API 密钥
            'cert_path'          => storage_path() . '/app/certificate/apiclient_cert.pem',
            'key_path'           => storage_path() . '/app/certificate/apiclient_key.pem',
            'notify_url'         => route('Api.Mall.refundBack'),
        ];

        return $config;
    }

    /**
     * 退款接口（订单不可为空）
     * @param Orders $thisOrder
     * @param $reason
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function Refund(Orders $thisOrder,$reason,$refundNum){
//        $config = DomainManager::getUnPayConfig($thisOrder);
        $config = self::refundConfig();
        $app = Factory::payment($config);
        $result = $app->refund->byOutTradeNumber($thisOrder->order_num, $refundNum, $thisOrder->pay_amount * 100, $thisOrder->pay_amount * 100, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_account' => 'REFUND_SOURCE_RECHARGE_FUNDS',
            'refund_desc' => $reason,
            'notify_url' => route('Api.Mall.refundBack'),
        ]);

        return $result;
    }

    /**
     * 退款查询接口（订单不可为空）
     * @param Orders $thisOrder
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function selectRefund(Orders $thisOrder){
        $config = DomainManager::getUnPayConfig($thisOrder);
        $app = Factory::payment($config);
        $result = $app->refund->queryByOutTradeNumber($thisOrder->order_num);
        return $result;
    }
}
